package com.daou.smartpush.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.daou.smartpush.common.util.Message;
import com.daou.smartpush.common.validator.CreateCompanyValidator;
import com.daou.smartpush.domain.company.Company;
import com.daou.smartpush.service.company.CompanyService;


@Controller
@RequestMapping("/company")
public class CompanyController {

	@Autowired
	CompanyService companyService;
	
	@RequestMapping(value="/create", method = RequestMethod.GET)
	public String createCompany(@ModelAttribute("company") Company company){
		return "createCompany";
	}
	
	@RequestMapping(value="/createResult" , method = RequestMethod.POST)
	public String createCompanyResult(@ModelAttribute("company") Company company, BindingResult result){
		Company resultCompany;
		try {
			new CreateCompanyValidator().validate(company, result);
			
			if(result.hasErrors()){
				return "createCompany";
			}
			
			//email check
			if(!company.getEmail().contains("@")){
				result.rejectValue("error_msg", "", Message.getMessage("error.company.wrongEmailType"));
				return "createCompany";
			}
			
			resultCompany = companyService.selectCompany(company.getCompanyName());
			
			if(resultCompany != null){
				result.rejectValue("error_msg", "", Message.getMessage("error.company.existCompany"));
				return "createCompany";
			}
			
			resultCompany = companyService.insetCompany(company);
			
			if(resultCompany == null){
				result.rejectValue("error_msg", "", Message.getMessage("error.company.error"));
				return "createCompany";
			}
		} catch (Exception e) {
			result.rejectValue("error_msg", "", Message.getMessage("error.company.error"));
			return "createCompany";
		}
		
		return "redirect:/";
	}

}
